<template>
    <el-row :gutter="20">
        <el-col :span="20">
            <!-- Markdown 编辑器-->
            <v-md-editor v-model="blogFrom.blogContent"
                         left-toolbar="undo redo clear title | h bold italic strikethrough quote | ul ol table | link image code tip align | save "
                         :toolbar="toolbar"
                         :disabled-menus="[]"
                         :include-level="[1,2,3]"
                         :default-show-toc="false"
                         @upload-image="handleUploadImage"
                         @save="save"
                         height="90vh">
            </v-md-editor>
        </el-col>

        <el-col :span="4">
            <el-form :model="blogFrom"
                     :rules="rules"
                     ref="formRef"
                     label-width="auto"
                     label-position="top">
                <el-form-item label="标题:" prop="blogTitle">
                    <el-input v-model="blogFrom.blogTitle" type="textarea" minlength="2" maxlength="40"
                              show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="摘要:" prop="blogAbstract">
                    <el-input v-model="blogFrom.blogAbstract" type="textarea" maxlength="200"
                              show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="分类:" prop="blogCategoryId">
                    <el-select v-model="blogFrom.blogCategoryId" filterable clearable style="width: 100%;"
                               placeholder="Select category">
                        <el-option
                                v-for="item in categories"
                                :key="item.categoryId"
                                :label="item.categoryName"
                                :value="item.categoryId"
                                :disabled="!item.isUse"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="标签（多选）:">
                    <el-select v-model="blogFrom.tagIds"
                               multiple
                               clearable
                               filterable
                               style="width: 100%;" placeholder="Select Tag">
                        <el-option
                                v-for="item in tags"
                                :key="item.tagId"
                                :label="item.tagName"
                                :value="item.tagId"
                                :disabled="!item.isUse"
                        />
                    </el-select>
                </el-form-item>

                <!-- 图片 -->
                <el-form-item>
                    <template #label>
                        封面：
                        <el-button text @click="choseInAlbum">从相册选择</el-button>
                    </template>
                    <el-upload
                            class="avatar-uploader"
                            name="Img"
                            :auto-upload="true"
                            action="/api/blog/uploadImg"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="getUploadImgUrl" :src="getUploadImgUrl" class="avatar"/>
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus/>
                        </el-icon>
                        <!--<p v-else class="avatar-uploader-text">点击上传</p>-->
                    </el-upload>
                </el-form-item>

                <el-form-item label="状态:">
                    <el-radio-group v-model="blogFrom.blogStatus">
                        <el-radio :label="true" size="default">发布</el-radio>
                        <el-radio :label="false" size="default">草稿</el-radio>
                    </el-radio-group>
                    <!--草稿-->
                    <!--<el-switch style="margin: 0 10px" v-model="blogFrom.blogStatus"/>-->
                    <!--发布-->
                </el-form-item>

                <el-form-item label="评论:">
                    关
                    <el-switch style="margin: 0 10px" v-model="blogFrom.enableComment"/>
                    开
                </el-form-item>
                <el-form-item label="置顶:">
                    否
                    <el-switch style="margin: 0 10px" v-model="blogFrom.isTop"/>
                    是
                </el-form-item>

                <el-form-item label="删除:">
                    留存
                    <el-switch style="margin: 0 10px" v-model="blogFrom.isDeleted"/>
                    已经删除
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="save">保存</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>


  <!-- 选择封面的对话框 -->
    <el-dialog
            v-model="dialogVisible"
            title="从相册选择"
            width="70%"
            :before-close="handleClose"
    >
        相册：
        <el-select v-model="choseAlbumId" placeholder="Select Album" @change="getPictures">
            <el-option
                    v-for="album in albums"
                    :key="album.albumId"
                    :label="album.albumName"
                    :value="album.albumId"
            />
        </el-select>
        <br>
        图片：<br>
        <el-radio-group v-model="chosePicUrl">
            <template v-for="(pic,index) in pictures">
                <div style="text-align: center;width: 14%">
                    <el-image style="height: 100px;width: 90%;border: 1px solid #eeeeee;margin: 5px" fit="cover"
                              :src="pic.pictureUrl" @click="()=>{chosePicUrl=pic.pictureUrl}"></el-image>
                    <br>
                    <el-radio :label="pic.pictureUrl" size="large">{{ index }}</el-radio>
                </div>
            </template>
        </el-radio-group>
        <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="choseOk">
          确认
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
        </template>
    </el-dialog>
  <!--<v-md-preview :text="value"></v-md-preview>-->
</template>

<script>
import {ElMessage} from "element-plus";

export default {
    name: "EditBlog",
    props: ['id'],
    created() {
        // 监听路由参数的变化
        this.$watch(
            () => this.$route.params,
            (newParams, oldParams) => {
                // 对路由参数做出响应，0就初始化，其他就通过查询数据库初始化
                if (newParams.id == 0) {
                    console.log("初始化新增")
                    this.$data.blogFrom = this.$options.data().blogFrom
                    this.$data.uploadImgUrl = this.$options.data().uploadImgUrl
                } else {
                    this.init(newParams.id)
                }
            }
        )

        this.uploadCategories()
        this.uploadTags()
        if (this.id > 0) {
            this.init(this.id)
        }
    },
    computed: {
        getUploadImgUrl() {
            if (this.uploadImgUrl) {
                return this.uploadImgUrl
            } else {
                return ""
            }
        },
    },
    data() {
        return {
            uploadImgUrl: "",
            blogFrom: {
                blogId: null,
                // 作者id
                authorId: null,
                // 标题
                blogTitle: '',
                // 封面地址
                blogImg: '',
                // 博客内容
                blogContent: '',
                // 博客摘要
                blogAbstract: '',
                // 分类id
                blogCategoryId: null,
                // 发布状态
                blogStatus: true,
                // 是否允许评论
                enableComment: true,
                isDeleted: false,
                isTop: false,
                // 发布时间
                releaseTime: null,
                // 标签id
                tagIds: []
            },
            rules: {
                blogTitle: [
                    {required: true, message: '请输入标题', trigger: 'blur'},
                    {min: 2, max: 40, message: '标题长度应该在2-40位之间', trigger: 'blur'},
                ],
                blogAbstract: [
                    {required: true, message: '请输入摘要', trigger: 'blur'},
                    {max: 200, message: '摘要长度应该在200位之内', trigger: 'blur'},
                ],
                blogCategoryId: [
                    {required: true, message: '请选择分类', trigger: 'change'},
                ],
            },
            categories: [],
            tags: [],
            // 从相册选择封面
            dialogVisible: false,
            choseAlbumId: null,
            albums: [],
            chosePicUrl: '',
            pictures: [],

            //
            toolbar: {
                title: {
                    icon: 'v-md-icon-toc',
                    title: '开头标题及目录',
                    action(editor) {
                        editor.insert(function (selected) {
                            const prefix = '::: align-center';
                            const suffix = ':::';
                            const placeholder = '请输入标题';
                            const content = selected || placeholder;

                            return {
                                text: `${prefix}\n# ${content}\n${suffix}\n[[toc]]\n`,
                                selected: content,
                            };
                        });
                    },
                },
                align: {
                    icon: 'v-md-icon-horizontal',
                    title: '对齐',
                    menus: [
                        {
                            name: 'align-left',
                            text: '左对齐',
                            action(editor) {
                                editor.insert(function (selected) {
                                    const prefix = '::: align-left';
                                    const suffix = ':::';
                                    const placeholder = '请输入文本';
                                    const content = selected || placeholder;

                                    return {
                                        text: `${prefix}\n${content}\n${suffix}`,
                                        selected: content,
                                    };
                                });
                            },
                        },
                        {
                            name: 'align-center',
                            text: '居中对齐',
                            action(editor) {
                                editor.insert(function (selected) {
                                    const prefix = '::: align-center';
                                    const suffix = ':::';
                                    const placeholder = '请输入文本';
                                    const content = selected || placeholder;

                                    return {
                                        text: `${prefix}\n${content}\n${suffix}`,
                                        selected: content,
                                    };
                                });
                            },
                        },
                        {
                            name: 'align-right',
                            text: '右对齐',
                            action(editor) {
                                editor.insert(function (selected) {
                                    const prefix = '::: align-right';
                                    const suffix = ':::';
                                    const placeholder = '请输入文本';
                                    const content = selected || placeholder;

                                    return {
                                        text: `${prefix}\n${content}\n${suffix}`,
                                        selected: content,
                                    };
                                });
                            },
                        },
                    ],
                },
            },
        }
    },
    methods: {
        // 如果带id就是编辑，就初始化
        async init(id) {
            let {data: result} = await this.$http.get('/api/blog/getBlogById', {params: {id: id}})
            let {code, dataMap} = result
            let tagIds = []
            if (code === 200 && dataMap.blog != null) {
                this.blogFrom.blogId = dataMap.blog.blogId
                this.blogFrom.authorId = dataMap.blog.authorId
                this.blogFrom.blogTitle = dataMap.blog.blogTitle
                this.blogFrom.blogImg = dataMap.blog.blogImg
                this.uploadImgUrl = dataMap.blog.blogImg
                this.blogFrom.blogContent = dataMap.blog.blogContent
                this.blogFrom.blogAbstract = dataMap.blog.blogAbstract
                this.blogFrom.blogCategoryId = dataMap.blog.blogCategoryId
                this.blogFrom.blogStatus = dataMap.blog.blogStatus
                this.blogFrom.enableComment = dataMap.blog.enableComment
                this.blogFrom.isDeleted = dataMap.blog.isDeleted
                this.blogFrom.isTop = dataMap.blog.isTop
                this.blogFrom.releaseTime = dataMap.blog.releaseTime
                if (dataMap.blog.tags) {
                    dataMap.blog.tags.forEach((item) => {
                        tagIds.push(item.tagId)
                    })
                }
                this.blogFrom.tagIds = tagIds
            }
        },
        async uploadCategories() {
            let {data: categories} = await this.$http.get('/api/category/getAllCategories')
            this.categories = categories
        },
        async uploadTags() {
            let {data: tags} = await this.$http.get('/api/tag/getAllTags')
            this.tags = tags
        },
        // 保存
        save() {
            this.$refs.formRef.validate(async (isValid) => {
                if (isValid) {
                    let {data: result} = await this.$http.post('/api/blog/save', this.blogFrom)
                    if (result.code === 200) {
                        ElMessage.success({showClose: true, message: result.msg})
                        this.blogFrom.blogId = result.dataMap.id
                    } else {
                        ElMessage.error({showClose: true, message: result.msg})
                    }
                } else {
                    ElMessage.error("表单填写有误！")
                }
            })
        },
        // 上传前检查文件格式和大小
        beforeAvatarUpload(rawFile) {
            // console.log(rawFile.type)
            // console.log(typeof rawFile.type)
            // console.log(rawFile.type !== 'image/jpeg')
            let allowTypes = ['image/jpeg', "image/jpg", 'image/png', 'image/webp', 'image/icon'];
            if (!allowTypes.includes(rawFile.type)) {
                ElMessage.error('文件格式不正确!')
                return false
            } else if (rawFile.size / 1024 / 1024 > 2) {
                ElMessage.error('文件大小不能大于 2MB!')
                return false
            }
            return true
        },
        // 上传成功修改预览
        handleAvatarSuccess(response) {
            console.log(response)
            let {code, dataMap} = response
            this.uploadImgUrl = dataMap.imgPath
            this.blogFrom.blogImg = dataMap.imgPath
        },
        // make上传图片
        async handleUploadImage(event, insertImage, files) {
            // 构建一个表单
            const formData = new FormData();
            // 表单添加图片
            formData.append('Img', files[0]);
            // axios 发起请求保存图片
            let {data} = await this.$http.post('/api/blog/uploadImg', formData, {
                headers: {'Content-Type': 'multipart/form-data'}
            })
            let {code, msg, dataMap} = data
            console.log(data)
            if (code === 200) {
                // 插入图片
                insertImage({
                    url: dataMap.imgPath,
                    desc: files[0].name,
                    width: 'auto',
                    height: 'auto',
                });
            } else {
                ElMessage.error({showClose: true, message: msg})
            }
        },
        async choseInAlbum() {
            this.dialogVisible = true
            let {data: albumRes} = await this.$http.get('/api/album/getAllAlbums')
            this.albums = albumRes.dataMap.albums

        },
        async getPictures() {
            let {data: result} = await this.$http.get("/api/picture/getPicturesByAlbumID", {params: {albumId: this.choseAlbumId}})
            this.pictures = result.dataMap.pictureList
        },
        choseOk() {
            this.blogFrom.blogImg = this.chosePicUrl
            this.uploadImgUrl = this.chosePicUrl
            this.dialogVisible = false
        },
        handleClose() {
            this.choseAlbumId = null
            this.albums = []
            this.chosePicUrl = ''
            this.pictures = []
            this.dialogVisible = false
        }
    },
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 100%;
    height: 100px;
    display: block;
    /*margin-left: 30px;*/
    border-radius: 20px;
}

.avatar-uploader {
    border: 1px solid #8c939d;
    border-radius: 20px;
    margin-left: 0;
    height: 100px;
    width: 100%;
    cursor: pointer;
    /*position: relative;*/
    /*溢出被裁剪*/
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    display: flex;

}


.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 100px;
    /*padding-left: 100px;*/
    /*margin-left: 50%;*/
    align-items: center;
    /*text-align: center;*/
}
</style>